package org.internna.ossmoney.mvc;

import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.internna.ossmoney.model.Account;
import org.internna.ossmoney.model.Subcategory;
import org.internna.ossmoney.model.support.Interval;
import org.internna.ossmoney.model.AccountTransaction;
import org.internna.ossmoney.model.security.UserDetails;

import static org.springframework.util.StringUtils.hasText;

public abstract class AbstractTransactionController {

	protected UserDetails getCurrentUser() {
		return UserDetails.findCurrentUser();
	}

	protected final Set<Account> getAccounts() {
		return getAccounts(getCurrentUser());
	}

    protected final Set<Account> getAccounts(UserDetails user) {
        return user.getAccounts();
    }

    protected Interval getInterval(String intervals) {
    	return hasText(intervals) ? new Interval(intervals) : new Interval();
    }

    protected final List<AccountTransaction> getTransactions(String intervals, Subcategory subcategory, ModelMap modelMap) {
    	return getTransactions(getCurrentUser(), intervals, subcategory, modelMap);
    }

    protected final List<AccountTransaction> getTransactions(UserDetails user, String intervals, Subcategory subcategory, ModelMap modelMap) {
    	return getTransactions(user, getInterval(intervals), subcategory, modelMap);
    }

    protected final List<AccountTransaction> getTransactions(Interval interval, Subcategory subcategory, ModelMap modelMap) {
    	return getTransactions(getCurrentUser(), interval, subcategory, modelMap);
    }

    protected final List<AccountTransaction> getTransactions(UserDetails user, Interval interval, Subcategory subcategory, ModelMap modelMap) {
    	List<AccountTransaction> transactions = new ArrayList<AccountTransaction>();
    	modelMap.addAttribute("interval", interval);
    	Set<Account> accounts = getAccounts(user);
    	if (!CollectionUtils.isEmpty(accounts)) {
    		for (Account account : accounts) {
    			transactions.addAll(account.getTransactionsInPeriod(interval, subcategory, true));
    		}
    	}
    	return transactions;
    }

}
